package com.augmentum.springcloudproductservice.controller;

import com.augmentum.springcloudproductservice.common.ServerResult;
import com.augmentum.springcloudproductservice.dto.ProductDto;
import com.augmentum.springcloudproductservice.entity.ProductCategory;
import com.augmentum.springcloudproductservice.entity.ProductInfo;
import com.augmentum.springcloudproductservice.repository.ProductInfoRepository;
import com.augmentum.springcloudproductservice.service.ProductCategoryService;
import com.augmentum.springcloudproductservice.service.ProductInfoService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.ListIterator;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Resource
    private ProductCategoryService productCategoryService;

    @Resource
    private ProductInfoService productInfoService;

    @Resource
    private ProductInfoRepository productInfoRepository;

    @GetMapping("/list")
    public ServerResult<List<ProductCategory>> list() {
        List<ProductInfo> upAllProductInfo = productInfoService.findUpAllProductInfo();
        List<ProductCategory> productCategoryList = productCategoryService.findByCategoryType(upAllProductInfo.stream()
                .map(ProductInfo::getCategoryType)
                .distinct()
                .collect(Collectors.toList()));

        productCategoryList.forEach(category -> {
            ListIterator<ProductInfo> productInfoListIterator = upAllProductInfo.listIterator();
            while (productInfoListIterator.hasNext()) {
                ProductInfo next = productInfoListIterator.next();
                if (next.getCategoryType().equals(category.getCategoryType())) {
                    category.getProductInfos().add(next);
                    productInfoListIterator.remove();
                }
            }
        });


        return ServerResult.success(productCategoryList);
    }

    @GetMapping("/msg")
    public String hello(String name) {
        return "hello " + name;
    }


    @PostMapping("/products")
    public List<ProductInfo> findProductsByIds(@RequestBody List<String> productIds) {
        return productInfoRepository.findByProductIdIn(productIds);
    }

    @PutMapping("/products")
    public String decreaseStock(@RequestBody List<ProductDto> productDtos) {
        productInfoService.decreaseStock(productDtos);

        return "ok";
    }

}
